#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>


// 删除第一个参数（文件夹名）下所有的 .jpg .jif .png 文件
// 如要删除其他条件，将查找比对参数更换为你需要删除的关键字

int delet_all_images(const char* path);


int main(int argc, char** argv)
{
    delet_all_images(argv[1]);

    return 0;
}


int delet_all_images(const char* path)
{
    DIR* dirp = NULL;
    struct dirent* d = NULL;
    char* file_name = NULL, *p = NULL;
    struct stat st;
    int cnt = 0;

    dirp = opendir(path);

    if(NULL == dirp)
    {
        return 0;
    }

    // chdir, getcwd

    file_name = (char*)malloc(4097);
    strcpy(file_name, path);

    if(file_name[strlen(file_name) - 1] != '/')
        strcat(file_name, "/");

    p = file_name + strlen(file_name);

    while((d = readdir(dirp)) != NULL)
    {
        if(strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0)
            continue;

        strcpy(p, d->d_name);
        // printf("%s\n", file_name);

        if(-1 == stat(file_name, &st))
            continue;

        if(S_ISREG(st.st_mode))
        {
            printf("%s\n", file_name);

            if(strcasecmp(d->d_name + strlen(d->d_name) - 4, ".jpg") == 0 
                || strcasecmp(d->d_name + strlen(d->d_name) - 4, ".gif") == 0
                || strcasecmp(d->d_name + strlen(d->d_name) - 4, ".png") == 0)
            {
                unlink(file_name);
                cnt++;
            }
        }

        if(S_ISDIR(st.st_mode))
        {
            cnt += delet_all_images(file_name);
        }
    }

    free(file_name);

    closedir(dirp);

    return cnt;
}

